<?php
/**
 * Created by PhpStorm.
 * User: Ysll <754060604@qq.com>
 * Date: 2017/9/8
 * Time: 9:10
 */

include_once __DIR__ . '/../http/ResponseResult.php';
include_once 'SessionService.php';
include_once 'TopicCategoryService.php';
/**
 * @param $category_id
 * @param $page
 * @param int $pageSize
 * @return stdClass
 */
function getTopicByCategoryId($category_id, $page, $pageSize = 10)
{
    $db = require __DIR__ . '/DatabaseService.php';
    $pagination = new stdClass();
    // 每页显示几个
    $pagination->per_page = $pageSize;
    // 当前页
    $pagination->current_page = $page;
    $result = mysqli_query($db, "select count(*) count from topics t, users u where t.topics_category_id = $category_id and t.is_deleted = FALSE and t.users_id = u.id;");
    $pagination->total = mysqli_fetch_assoc($result)['count'];
    $start = $pagination->current_page * $pagination->per_page - $pagination->per_page;
    $result = mysqli_query($db, "select t.id, t.title, t.is_recommend, u.access from topics t, users u where t.topics_category_id = $category_id and t.is_deleted = FALSE and t.users_id = u.id LIMIT {$start},{$pagination->per_page}");
    $pagination->topics = mysqli_fetch_all($result, MYSQLI_ASSOC);
    $pagination->last_page = (int)ceil($pagination->total / $pagination->per_page);
    return $pagination;
}

function createTopic()
{
    $db = require __DIR__ . '/DatabaseService.php';
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        responseError(1000, 'Not Find 404');
    }

    if (!checkLogin()) {
        responseError(2000, 'Not Login');
    }
    $user = getUser();
    $data = $_POST;
    $title = isset($data['title']) ? $data['title'] : null;
    $category_id = (int)(isset($data['category_id']) ? $data['category_id'] : 0);
    $content = isset($data['content']) ? $data['content'] : null;

    if ($title == null || $category_id == 0 || $content == null) {
        responseError(3000, '缺少参数');
    }

    if (empty(getTopicCategoryById($category_id))) {
        responseError(4000, '无法找到类别');
    }
    $stmt = mysqli_prepare($db, "INSERT INTO `topics` (`users_id`, `title`, `topics_category_id`, `description`) VALUES (?, ?, ?, ?)");
    $title = mysqli_real_escape_string($db, $title);
//    $content = mysqli_real_escape_string($db, $content);
    if (mysqli_stmt_bind_param($stmt, 'isis', $user['users_id'], $title, $category_id, $content) == false) {
        responseError(5000, '无法创建帖子');
    }

    if (!mysqli_stmt_execute($stmt)) {
        responseError(6000, '无法创建帖子');
    }
    return mysqli_stmt_insert_id($stmt);
}

function findTopicById($id) {
    $db = require __DIR__ . '/DatabaseService.php';
    $result = mysqli_query($db, "SELECT * FROM topics WHERE id = {$id}");
    if ($result == false) {
        return null;
    }
    return mysqli_fetch_assoc($result);
}

function findTopicByUsers($users_id) {
    $db = require __DIR__ . '/DatabaseService.php';
    $result = mysqli_query($db, "SELECT * FROM topics WHERE users_id = {$users_id}");
    if ($result == false) {
        return null;
    }
    return mysqli_fetch_all($result, MYSQLI_ASSOC);
}

/**
 * @param $question
 * @param $page
 * @param int $limit
 * @return object
 */
function getTopicPagination($page, $question, $limit = 20)
{
    $db = require 'DatabaseService.php';
    $topics = new stdClass();
    $result = mysqli_query($db, "SELECT count(*) count FROM topics WHERE is_deleted = FALSE AND title LIKE '%{$question}%'");
    $topics->total = mysqli_fetch_assoc($result)['count'];
    $topics->per_page = $limit;
    $topics->current_page = $page;
    $topics->last_page = (int)ceil($topics->total / $topics->per_page);
    $start = $topics->per_page *  $topics->current_page - $topics->per_page;
    $result = mysqli_query($db, "SELECT * FROM topics WHERE is_deleted = FALSE AND title LIKE '%{$question}%' LIMIT $start,{$limit}");
    $topics->topic = mysqli_fetch_all($result, MYSQLI_ASSOC);
    foreach ($topics->topic as $key => $topic) {
        $result = mysqli_query($db, "select * from users_data where users_id = {$topic['users_id']}");
        $topics->topic[$key]['user'] = mysqli_fetch_assoc($result);
        $result = mysqli_query($db, "select * from topics_category where id = {$topic['topics_category_id']}");
        $topics->topic[$key]['category'] = mysqli_fetch_assoc($result);
    }
    return $topics;
}

function updateTopic($id, $data) {
    $sql = 'UPDATE topics SET';
    foreach ($data as $key => $value) {
        $sql .= " $key = '$value',";
    }
    $sql = rtrim($sql, ',') . " WHERE id = $id";
    $db = require 'DatabaseService.php';
    $result = mysqli_query($db, $sql);
    if ($result == false || mysqli_errno($db)) {
        $_SESSION['error_code'] = mysqli_errno($db);
        $_SESSION['error_data'] = mysqli_error($db);
        return false;
    }
    return true;
}
